import router from './router'
import { getCookie } from './utils/cookie'
import userStore from '@/stores/user'
import { getRouters } from '@/api/login'
import { noMathPage } from './router'
import { initRouter } from './hooks/permission'
import { useBasicStore } from './stores/basic'
import { getUserInfo } from './api/user'
import { constRoutes } from './router/constant'

const whiteList = ['/login']

router.beforeEach(async (to, from) => {
    const user = userStore()
    const token = getCookie('token')//sessionStorage.getItem('token')

    if (token) {

        if (to.path === '/login') {
            return '/'
        } else {
            try {
                if (!user.userInfo?.userId) {
                    const result = await getUserInfo()
                    user.userInfo = result.user
                    user.setUserInitData(result)
                }
                // 第一次 清洗路由 添加路由
                if (!user.routerList.length) {
                    console.log('init user.routerList', to.path)
                    const asyncRouters = await getRouters()
                    user.routerList = [...asyncRouters, ...constRoutes]
                    initRouter(asyncRouters) // 初始化注册全局路由
                    if (to.path === '/' && !to?.name) {
                        return {
                            path: '/',
                            replace: true
                        }
                    }
                    return  to.fullPath
                } else {
                    return true
                }
            } catch (e) {
                return `/login?redirect=${to.path}`
            }
        }

    } else {
        if(whiteList.includes(to.path)) {
            return true
        } else {
            return '/login'
        }
    }
})
